package com.zsy.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zsy.dao.CategoryDao;
import com.zsy.dao.DishDao;
import com.zsy.dao.SetmealDao;
import com.zsy.exception.CustomException;
import com.zsy.pojo.Category;
import com.zsy.pojo.Page;
import com.zsy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categorydDao;
    @Autowired
    private DishDao dishDao;
    @Autowired
    private SetmealDao setmealDao;


    @Override
    public void save(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        categorydDao.save(category);
    }

    @Override
    public Page<Category> page(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        List<Category> list = categorydDao.page();

        PageInfo<Category> categoryPageInfo = new PageInfo<>(list);

        Page<Category> categoryPage = new Page<>(categoryPageInfo.getList(), categoryPageInfo.getTotal(), categoryPageInfo.getSize(), categoryPageInfo.getPageSize());

        return categoryPage;
    }

    @Override
    public void delete(long id) {
        long byId = dishDao.findById(id);
        if (byId > 0){
            throw new CustomException("此类别关联了其他菜品，无法删除");
        }
        long byId1 = setmealDao.findById(id);
        if (byId1>0) {
            throw new CustomException("此类别关联了其他菜品，无法删除");
        }
        categorydDao.delete(id);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());

        categorydDao.update(category);

    }

    @Override
    public List<Category> findByType(Integer type) {

        return categorydDao.findByType(type);
    }
}
